package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequirePermission;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IRoleService roleService;

    //处理查询所有部门的请求
    @RequestMapping("/list")
    @RequirePermission(name = "员工列表",expression = "employee:list")
    public String list(Model model,@ModelAttribute("qo") EmployeeQueryObject qo){


        //只看本部门
        Employee employee = UserContext.getCurrentUser();
        Department department = employeeService.get(employee.getId()).getDept();
        //传入复选框的状态,true 就根据用户部门id筛选,false就直接全部筛选
        if (qo.getDeptCheck()){

            qo.setDeptId(department.getId());
        }
        model.addAttribute("pageResult",employeeService.query(qo));

        //查询所有部门数据,存在模型
        List<Department> departments = departmentService.listAll();
        //处理分页查询部门的请求
        model.addAttribute("departments",departments);

        return "employee/list";  //  /WEB-INF/views/employee/list.ftl
    }

    @RequestMapping("/batchDelete")
    @ResponseBody
    public JsonResult batchDelete(/*@RequestParam("ids[]")*/ Long[] ids){
            employeeService.batchDelete(ids);
            return new JsonResult();
    }




    //处理删除请求
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id){
        try {
        if (id!=null){
            employeeService.delete(id);
        }
            return new JsonResult();
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult(false,"操作失败");
        }

    }

    //处理去新增请求
    @RequestMapping("/input")
    public String input(Long id,Model model){

        List<Department> departments = departmentService.listAll();
        //查询所有部门往模型存入，提供数据，让员工新增修改时显示出来以供用户选择
        model.addAttribute("departments",departments);

        List<Role> roles = roleService.listAll();
        model.addAttribute("roles",roles);
        //如果传id就传去修改
        if (id!=null){
            model.addAttribute("employee",employeeService.get(id));
        }
        return "employee/input";
    }

    //处理新增请求
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    @RequirePermission(name = "员工添加/更新",expression = "employee:saveOrUpdate")
    public JsonResult saveOrUpdate(Employee employee,Long[] ids){
        if (employee.getId()!=null){
            //修改
            employeeService.update(employee,ids);
        }else {
            //新增
            employeeService.save(employee,ids);
        }
        return new JsonResult();
    }

    /**
     * 检验用户名是否存在
     * valid 的key是插件规定的,不能改
     * @param name
     * @return
     */
    @RequestMapping("/checkName")
    @ResponseBody
    public HashMap checkName(String name){
        Employee employee = employeeService.selectByName(name);
        HashMap map = new HashMap();
        map.put("valid",employee==null);
        return map;
    }

    /**
     * 导出
     * @param response
     * @throws IOException
     */
    @RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws IOException {
        //设置文件下载的响应头
        response.setHeader("Content-Disposition","attachment;filename=employee.xls");

        //在业务层提供一个导出excel的方法
        Workbook wb = employeeService.exportXls();
        //把excel的数据输出到浏览器的响应流中
        wb.write(response.getOutputStream());

    }

    /**
     * 导入
     */
    @RequestMapping("/importXls")
    @ResponseBody
    public JsonResult importXls(MultipartFile file) throws IOException {//MultipartFile file 用于封装文件

        employeeService.importXls(file);
        return new JsonResult();
    }

    /*//处理重置密码请求
    @RequestMapping("/resetPwd")
    @ResponseBody
    public JsonResult resetPwd(String newPassword,Model model){
        try{
        List<Employee> employees = employeeService.listAll();
        model.addAttribute("employee", employees);
        for (Employee employee :employees) {
            employeeService.resetPwd(newPassword,employee.getId());
        }
            return new JsonResult();
        } catch(Exception e) {
            e.printStackTrace();
            return new JsonResult(false, e.getMessage());
        }

    }*/

    //处理修改状态请求
    @RequestMapping("/change")
    @ResponseBody
    public JsonResult change(Long id){
        boolean status = employeeService.get(id).isStatus();
        if (id!=null){
            employeeService.change(status,id);
        }
        return new JsonResult();
    }
}
